package org.lex.ftp.ui;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class PosPane extends JPanel {
	public static final String MAXIMIZE = "Maximize";
	public static final String RESTORE = "Restore";
	/*
	 * ��ʾλ�ã����õ���: NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST
	 */
	private int position = SwingConstants.CENTER;
	private String state = RESTORE;
	private JPopupMenu popup = null;
	private JMenuItem maximizeMenuItem = null;
	private JMenuItem restoreMenuItem = null;
	private ActionListener actionListener = null;
	private ActionListener groupListener = null;

	public PosPane(JComponent component, int position, ActionListener l) {
		super(new BorderLayout());
		this.add(component, BorderLayout.CENTER);
		component.setInheritsPopupMenu(true);
		this.position = position;
		this.actionListener = l;
		this.setComponentPopupMenu(this.getPopup());
		this.setBorder(null);
	}

	public int getPosition() {
		return this.position;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	@Override
	protected void paintBorder(Graphics g) {
	}

	private JPopupMenu getPopup() {
		if (null == this.popup) {
			popup = new JPopupMenu();
			popup.add(this.getRestoreMenuItem());
			popup.add(this.getMaximizeMenuItem());
		}
		return this.popup;
	}

	private JMenuItem getRestoreMenuItem() {
		if (null == restoreMenuItem) {
			restoreMenuItem = this.createMenuItem(RESTORE);
			restoreMenuItem.setMnemonic('R');
			restoreMenuItem.setEnabled(false);
		}
		return restoreMenuItem;
	}

	private JMenuItem getMaximizeMenuItem() {
		if (null == maximizeMenuItem) {
			maximizeMenuItem = this.createMenuItem(MAXIMIZE);
			maximizeMenuItem.setMnemonic('x');
		}
		return maximizeMenuItem;
	}

	private JMenuItem createMenuItem(String key) {
		JMenuItem item = new JMenuItem();
		item.setText(key);
		item.setName(Integer.toString(this.position));
		item.setActionCommand(key);
		item.addActionListener(this.actionListener);
		item.addActionListener(this.getGroupListener());
		return item;
	}

	private ActionListener getGroupListener() {
		if (null == this.groupListener) {
			this.groupListener = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if (e.getSource() == getRestoreMenuItem()) {
						getRestoreMenuItem().setEnabled(false);
						getMaximizeMenuItem().setEnabled(true);
					} else {
						getRestoreMenuItem().setEnabled(true);
						getMaximizeMenuItem().setEnabled(false);
					}
				}
			};
		}
		return groupListener;
	}
}
